﻿#include <Windows.h>
#include <tchar.h>

#include <iostream>

#include "device.h"

using namespace windows::user;

int main() {
  DWORD error;
  Device device;
  WCHAR time_buffer1[24], time_buffer2[24];
  DWORD time_buffer_size1, time_buffer_size2;
  OVERLAPPED overlapped1, overlapped2;

  do {
    error = device.Open(TEXT("Asynchronous"), TRUE);
    if (ERROR_SUCCESS != error) {
      _tprintf(TEXT("main device.Open fail, Error=%d\n"), error);
      break;
    }
    _tprintf(TEXT("device.Open success\n"));

    time_buffer_size1 = sizeof(time_buffer1);
    RtlZeroMemory(&overlapped1, sizeof(overlapped1));
    overlapped1.hEvent = CreateEvent(NULL, FALSE, FALSE, NULL);
    if (!overlapped1.hEvent) {
      _tprintf(TEXT("First CreateEvent fail, error=%d\n"), GetLastError());
      break;
    }
    error = device.ReadAsync(time_buffer1, time_buffer_size1, overlapped1);
    if (ERROR_SUCCESS != error && ERROR_IO_PENDING != error) {
      _tprintf(TEXT("First device.Read fail, error=%d\n"), error);
      break;
    }
    _tprintf(TEXT("First devoce.Read Success\n"));
    
    time_buffer_size2 = sizeof(time_buffer2);
    RtlZeroMemory(&overlapped2, sizeof(overlapped2));
    overlapped2.hEvent = CreateEvent(NULL, FALSE, FALSE, NULL);
    error = device.ReadAsync(time_buffer2, time_buffer_size2, overlapped2);
    if (ERROR_SUCCESS != error && ERROR_IO_PENDING != error) {
      _tprintf(TEXT("Second device.Read fail, error=%d\n"), error);
      break;
    }
  _tprintf(TEXT("Second devoce.Read Success\n"));
  } while (false);
  device.Close();

  if (overlapped1.hEvent) {
    error = WaitForSingleObject(overlapped1.hEvent, 5000);
    if (WAIT_OBJECT_0 == error) {
      wprintf(L"time=%s\n", time_buffer1);
    } else {
      _tprintf(TEXT("First WaitForSingleObject fail, error=%d\n"), error);
    }
    CloseHandle(overlapped1.hEvent);
  }

  if (overlapped2.hEvent) {
    error = WaitForSingleObject(overlapped2.hEvent, 5000);
    if (WAIT_OBJECT_0 == error) {
      wprintf(L"time=%s\n", time_buffer2);
    } else {
      _tprintf(TEXT("Second WaitForSingleObject fail, error=%d\n"), error);
    }
    CloseHandle(overlapped2.hEvent);
  }
 
  
  return EXIT_SUCCESS;
}

